package com.springboot.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.mall.exception.MallException;
import com.springboot.mall.exception.MallExceptionEnum;
import com.springboot.mall.model.entity.Category;
import com.springboot.mall.model.mappers.CategoryMapper;
import com.springboot.mall.model.request.AddCategoryRequest;
import com.springboot.mall.model.request.UpdateCategoryRequest;
import com.springboot.mall.model.vo.CategoryVO;
import com.springboot.mall.service.CategoryServcice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
 *
 *目录分类实现类
 *@data 2022-05-09
 */
@Service("categoryServcice")
public class CategoryServciceImpl implements CategoryServcice {

    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public void add(AddCategoryRequest addCategoryRequest) {
        Category category = new Category();
        BeanUtils.copyProperties(addCategoryRequest,category);
        Category categoryOld = categoryMapper.selectByName(addCategoryRequest.getName());
        if (categoryOld != null){
            throw new MallException(MallExceptionEnum.NAME_EXISTED);
        }
        int count = categoryMapper.insertSelective(category);
        if (count == 0){
            throw new MallException(MallExceptionEnum.CREATE_FAILED);
        }
    }

    @Override
    public void update(UpdateCategoryRequest updateCategoryRequest) {
        Category category = new Category();
        BeanUtils.copyProperties(updateCategoryRequest,category);

        if (updateCategoryRequest.getName() != null){
            //首先判断 更新的名字是否在数据库中已经存在（名字不能重复）
            Category categoryOld = categoryMapper.selectByName(updateCategoryRequest.getName());
            //这里的更新逻辑需要捋一下
            //如果不为空，则数据库已经存在该名字，但是如果知识想更新这个名字的层级，则必然是可以查到这条数据的
            //所以需要验证这条数据的id和传过来的id是否一致
            if(categoryOld != null && !categoryOld.getId().equals(updateCategoryRequest.getId())){
                throw new MallException(MallExceptionEnum.NAME_EXISTED);
            }
            int i = categoryMapper.updateByPrimaryKeySelective(category);
            if (i == 0){
                throw new MallException(MallExceptionEnum.UPDATE_FAILED);
            }

        }
    }

    @Override
    public void delete(Integer id) {
        Category categoryOld = categoryMapper.selectByPrimaryKey(id);
        //查不到记录，无法删除
        if (categoryOld == null){
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
        int count = categoryMapper.deleteByPrimaryKey(id);
        if (count == 0){
            throw new MallException(MallExceptionEnum.DELETE_FAILED);
        }
    }

    @Override
    public PageInfo listForAdmin(Integer pagenum, Integer pageSize){
        PageHelper.startPage(pagenum,pageSize,"type,order_num");
        List<Category> categories = categoryMapper.selectList();
        //封装成Info可以传递出很多分页信息，方便浏览器处理
        PageInfo pageInfo = new PageInfo(categories);
        return pageInfo;
    }

    @Override
    //@Cacheable(value = "listForCustomer")
    public List<CategoryVO> listForCustomer(Integer parentId){
        ArrayList<CategoryVO> categoryVOList = new ArrayList<>();
        recursivelyFindCategories(categoryVOList,parentId);
        return categoryVOList;
    }

    //recursively递归
    public void recursivelyFindCategories(List<CategoryVO> categoryVOList,Integer parentId){
        //递归获取所有子类别，并组合成一个"目录树"
        List<Category> categories = categoryMapper.selectCategoriesByParentId(parentId);
        if (!CollectionUtils.isEmpty(categories)){
            for (int i = 0; i < categories.size(); i++) {
                Category category = categories.get(i);
                CategoryVO categoryVO = new CategoryVO();
                BeanUtils.copyProperties(category,categoryVO);
                categoryVOList.add(categoryVO);
                //开始递归
                recursivelyFindCategories(categoryVO.getChildCategory(),categoryVO.getId());
            }

        }
    }
    /*
    * 非递归
    *有个小问题，返回的是全部分类的列表，递归方法返回的是顶级分类的目录，消耗了很多时间，做了很多重复性的工作
    *再优化：
    * */
    /*@Override
    //@Cacheable(value = "listForCustomer")
    public List<CategoryVO> listForCustomer(){
        //获取全部分类
        List<Category> categoryList = categoryMapper.selectList();
        List<CategoryVO> categoryVOLists = new ArrayList<>();
        //将所有的实体类，转为新的实体类
        for (int i = 0; i < categoryList.size(); i++) {
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(categoryList.get(i),categoryVO);
            categoryVOLists.add(categoryVO);
        }

        //遍历全部条目
        for (int i = 0; i < categoryVOLists.size(); i++) {
            //判断是否是顶级元素
            if (categoryVOLists.get(i).getParentId() != 0){
                //为外层分类寻找父分类
                for (int j = 0; j <categoryVOLists.size(); j++) {
                    //循环判断是否是父分类
                    if (categoryVOLists.get(j).getId() == categoryVOLists.get(i).getParentId()){
                        //为空说明还没有加入子分类
                        if (categoryVOLists.get(j).getChildCategory() == null){
                            List<CategoryVO> categoryVOList = new ArrayList<>();
                            categoryVOList.add(categoryVOLists.get(i));
                            categoryVOLists.get(j).setChildCategory(categoryVOList);
                        }else{
                            categoryVOLists.get(j).getChildCategory().add(categoryVOLists.get(i));
                        }

                    }

                }

            }

        }
        return categoryVOLists;
    }*/

}
